﻿using System.Text.Json;

using Aliyun.OSS.Common;

using XServer.Managers;
using XServer.Models.DrawCards;
using XServer.Models.OSS;
using XServer.Systems;

namespace XServer.Utility.Pools
{
    public class PictureDownloadPoolTask : ITask
    {
        private readonly string _fileName;
        private readonly string _key;
        private OssConfig _config;
        private readonly object locker = new();
        private readonly ILogger _logger;

        public PictureDownloadPoolTask(string fileName, ILogger logger)
        {
            _logger = logger;
            _config = OssManager.Instance.GetConfig();
            _fileName = fileName;
            _key = Path.Combine(_config.PathFilter, _fileName);
        }

        public bool Execute()
        {
            try
            {
                var data = OssHelper.GetObject(_config, _key);
                if (data == null)
                {
                    return false;
                }

                string cachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "images", _fileName);
                lock (locker)
                {
                    File.WriteAllBytes(cachePath, data);
                }
                return true;
            }
            catch (OssException ex)
            {
                _logger.LogError($"文件下载异常: Error Code: {ex.ErrorCode}, RequestID:{ex.RequestId}, HostID:{ex.HostId}, Exception:\n{ex}");
                return false;
            }
            catch (Exception ex)
            {
                _logger.LogError($"文件下载异常: {ex}");
                return false;
            }
        }
    }
}
